package com.tech.connect.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.ksy.common.model.City;
import com.ksy.common.utils.BaseAdapter;
import com.ksy.common.utils.BaseHolder;
import com.ksy.common.utils.ThreadManager;
import com.ksy.common.view.HLineDivider;
import com.tech.connect.R;
import com.tech.connect.view.SideBar;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CityChooseActivity extends BaseActivity {

    private RecyclerView recycler;
    private BaseAdapter<City, BaseHolder> adapter;
    private List<City> allHotCity = new ArrayList<>();
    private List<City> allCityList = new ArrayList<>();
    private Handler handler = new Handler(Looper.getMainLooper());
    private LinearLayoutManager layoutManager;

    @Override
    protected boolean isShowHeadBar() {
        return true;
    }

    @Override
    protected void initImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar
                .fitsSystemWindows(false)
                .keyboardEnable(true)
                .init();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getHeadBar().setTitle("选择城市");
        setContentView(R.layout.activity_city_choose);
        initView();
        loadData();
        City cityAll = new City();
        cityAll.sort = "#";
        cityAll.name = "全国";

        City cityBeiJin = new City();
        cityBeiJin.sort = "☆";
        cityBeiJin.name = "北京市";
        cityBeiJin.lng = 116.40717d;
        cityBeiJin.lat = 39.90469d;
        cityBeiJin.id = 110000;

        City cityShangHai = new City();
        cityShangHai.sort = "☆";
        cityShangHai.name = "上海市";
        cityShangHai.lng = 121.4737d;
        cityShangHai.lat = 31.23037d;
        cityShangHai.id = 310000;


        City cityChengdu = new City();
        cityChengdu.sort = "☆";
        cityChengdu.name = "成都市";
        cityChengdu.lng = 104.06476;
        cityChengdu.lat = 30.5702;
        cityChengdu.id = 510100;

        City cityHangzhou = new City();
        cityHangzhou.sort = "☆";
        cityHangzhou.name = "杭州市";
        cityHangzhou.lng = 120.15515;
        cityHangzhou.lat = 30.27415;
        cityHangzhou.id = 330100;


        allHotCity.add(cityAll);
        allHotCity.add(cityShangHai);
        allHotCity.add(cityHangzhou);
        allHotCity.add(cityBeiJin);
        allHotCity.add(cityChengdu);

    }

    private void loadData() {
        ThreadManager.getNormalPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream open = getAssets().open("city.json");
                    byte[] buffer = new byte[open.available()];
                    open.read(buffer);
                    open.close();
                    String jobJson = new String(buffer, "UTF-8");
                    Gson gson = new Gson();
                    final List<City> areas = gson.fromJson(jobJson, new TypeToken<List<City>>() {
                    }.getType());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            initAllCityAdapter(areas);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void initView() {
        recycler = findViewById(R.id.recycler);

        recycler.addItemDecoration(new HLineDivider());
        layoutManager = new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(layoutManager);

        SideBar sideBar = findViewById(R.id.sideBar);
        sideBar.setIndexListener(new SideBar.IndexListener() {
            @Override
            public void onIndexAt(String tag) {
                showLog(tag);
                int index = locationIndex(tag);
                if (index >= 0 && adapter.getItemCount() > index) {
                    layoutManager.scrollToPositionWithOffset(index, 0);
                }

            }
        });
    }

    private int locationIndex(String tag) {
        for (int i = 0; i < allCityList.size(); i++) {
            City city = allCityList.get(i);
            if (isSame(city.sort, tag)) {
                return i;
            }
        }
        return -1;
    }

    private void initAllCityAdapter(List<City> cityList) {
        allCityList.clear();
        allCityList.addAll(allHotCity);
        if (cityList != null) {
            allCityList.addAll(cityList);
        }
        if (adapter == null) {
            adapter = new BaseAdapter<City, BaseHolder>(R.layout.item_layout_city_choose, allCityList) {
                @Override
                protected void convert(BaseHolder helper, int position) {
                    City city = allCityList.get(position);
                    TextView tvHeader = helper.getView(R.id.tvHeader);
                    tvHeader.setText(city.sort);

                    if (position == 0) {
                        tvHeader.setVisibility(View.GONE);
                    } else {
                        City beforeCity = allCityList.get(position - 1);
                        if (isSame(beforeCity.sort, city.sort)) {
                            tvHeader.setVisibility(View.GONE);
                        } else {
                            tvHeader.setVisibility(View.VISIBLE);
                        }
                    }

                    TextView tvCity = helper.getView(R.id.tvCity);
                    tvCity.setText(city.name);
                }
            };
            adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    City city = allCityList.get(position);
                    if (TextUtils.equals(city.name, "全国")) {
                        return;
                    }
                    Intent intent = new Intent();
                    intent.putExtra("data", city);
                    setResult(RESULT_OK, intent);
                    destroyActivity();
                }
            });
            recycler.setAdapter(adapter);
        }
        adapter.notifyDataSetChanged();
    }

}
